package cn.interestingshop.utils;

import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Set;

public class YzmUtils {

    public int yzm(HttpServletRequest request, HttpServletResponse response) {
        //生产环境请求地址：app.cloopen.com
        String serverIp = "app.cloopen.com";
        //请求端口
        String serverPort = "8883";
        // TODO 主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
        String accountSId = "2c9488768658b82f018682419fb30c1f";
        String accountToken = "a1c06b1ef04642389e2a9c9c235963f2";
        // TODO 请使用管理控制台中已创建应用的APPID
        String appId = "2c9488768658b82f01868241a0de0c26";

        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);

        int num = (int) (Math.random() * 9000)+1000;

        // 模拟验证码
        String code = String.valueOf(num);
        // TODO 手机号
        String to = request.getParameter("phone");
        // 短信模板 测试接口默认为 1
        String templateId= "1";
        String[] datas = {code, "1"}; // 验证码， 过期时间五分钟

        // String subAppend="1234";  //可选 扩展码，四位数字 0~9999
        // String reqId="fadfafas";  //可选 第三方自定义消息id，最大支持32位英文数字，同账号下同一自然天内不允许重复
        HashMap<String, Object> result=null;
        try {
            result = sdk.sendTemplateSMS(to, templateId, datas);
        }catch (Exception e){
            e.printStackTrace();
        }
        // HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas,subAppend,reqId);

        if("000000".equals(result.get("statusCode"))){
            //正常返回输出data包体信息（map）
            HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
            Set<String> keySet = data.keySet();
            for(String key:keySet){
                Object object = data.get(key);
                System.out.println(key +" = "+object);
            }

            request.getSession().setAttribute(to,num);
            request.getSession().setAttribute("data","1");
            request.getSession().setMaxInactiveInterval(1*60);
        }else{
            //异常返回输出错误码和错误信息
            System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
            return -1;
        }

        return num;
    }
}
